package com.example.mardan_demo1.service.impl;

import com.example.mardan_demo1.mapper.UserMapper;
import com.example.mardan_demo1.pojo.*;
import com.example.mardan_demo1.pojo.QiYeYongHu.QiYeYongHu;
import com.example.mardan_demo1.service.UserService;
import com.example.mardan_demo1.utils.JWTUtil;
import com.example.mardan_demo1.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(BgsServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    public Result addUser(User user) {
        return Result.error("1111;");
    }

    public Result buMenLieBiao() {
        // 查询所有部门
        List<BuMen> bumenList = userMapper.getAllBuMen();
        return Result.success(bumenList);
    }

    @Override
    public Result addUser(String name, String username, String password, Integer buMenId, String role) {
        // 判断username是否存在
        User userInfo = userMapper.getUserInfoByUsername(username);
        logger.info("userInfo: " + userInfo);
        if ((userInfo != null)) {
            return Result.error("用户名已存在");
        }
        // 判断所选部门是否存在
        BuMen bumen = userMapper.getBumenById(buMenId);
        logger.info("bumen: " + bumen);
        if (bumen == null) { return Result.error("所选部门不存在");}
        // 新增用户
        userMapper.xinZengYongHu(name, username, password);
        // 获取用户id
        userInfo = userMapper.findByUserName(username);
        logger.info("userInfo" + userInfo);
        Integer userId = userInfo.getId();
        // 创建用户和部门关系表
        userMapper.sheZhiBuMenHeZhiWu(userId,buMenId,role);
        return Result.success("新增成功");
    }

    @Override
    public Result adminGetUserById(Integer userId) {
        return Result.success(userMapper.adminGetUserById(userId));
    }

    @Override
    @Transactional
    public Result adminUpdateUserInfo(Integer userId, String name, String password, Integer buMenId, String role) {
        // 判断用户是否存在
        User user = userMapper.getUserById(userId);
        logger.info("User" + user);
        if (user == null){ return Result.error("该用户不存在"); }
        // 判断部门是否存在
        BuMen bumen = userMapper.getBumenById(buMenId);
        logger.info("bumen" + bumen);
        if( bumen == null) {return Result.error("部门不存在");}
        // 都合格的话可以更新了，先更新user表中的name，password , 然后在关系表中的buMenId 和 role
        userMapper.updateUserNickNameAndPasswordById(userId,name, password);
        userMapper.updateBuMenAndRoleByUserId(userId, buMenId, role);
        return Result.success("操作成功");
    }

    public Result userUpdateDetail(User user) {
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        if (userInfo == null) { return Result.error("请先登录"); }
        Integer userId = (Integer) userInfo.get("id");
        // 判断用户是否存在
        User userInDb = userMapper.getUserById(userId);
        logger.info("userInDb" + userInDb);
        if (userInDb == null) { return Result.error("该用户不存在"); }
        // 都合格的话可以更新了
        user.setId(userId);
        userMapper.userUpdateDetail(user);
        return Result.success("修改成功");
    }

    public Result yongHuSheZhiZhiWu( Integer userId, Integer bumenId, String role){
        // 判断用户是否存在
        User user = userMapper.getUserInfo(userId);
        logger.info("User" + user);
        if (user == null) {return Result.error("用户不存在");}
        // 判断部门是否存在
        BuMen bumen = userMapper.getBumenById(bumenId);
        if (bumen == null) {return Result.error("部门不存在");}
        // 如果已经存在了关系就不能新增只能编辑
        BuMenHeYongHuGuanXi guanxibiao = userMapper.getBuMenHeYongHuGuanXiByYongHuId(userId);
        if (guanxibiao != null) {return Result.error("该关系已存在，只能修改");}
        // 给用户设置部门和职务
        userMapper.sheZhiBuMenHeZhiWu(userId, bumenId, role);
        return Result.success("设置成功");
    }

    public Result buMenXinZeng(String mingCheng, Integer xuHao) {
        logger.info("mingCheng=" + mingCheng);
        logger.info("xuHao=" + xuHao);
        userMapper.buMenXinZeng(mingCheng, xuHao);
        return Result.success("添加成功");
    }

    public Result getUserList(String name, String userName, Integer pageSize, Integer pageNum) {
        // 验证用户权限
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        String userRole = (String) userInfo.get("role");
        logger.info("userRole={}", userRole);
        if (!userRole.equals("admin")) {
            return Result.error("你不是管理员");
        }
        PageBean<User> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<User> as = userMapper.getUserList(name, userName);
        Page<User> p = (Page<User>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }

    /**
     * 根据token返回用户的id
     * @return id     */
    public Integer getUserIdFromToken(){
        Map<String, Object> map = ThreadLocalUtil.get();
        return (Integer)map.get("id");
    }
    @Override
    public Result updatePassWd(String oldPassWord, String newPassWord, String rePassWord){
        // 校验参数
        if (!StringUtils.hasLength(oldPassWord) || !StringUtils.hasLength(newPassWord) || !StringUtils.hasLength(rePassWord)){
            return Result.error("缺少必要参数");
        }
        // 原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = findUserByUserName(username);
        if (!loginUser.getPassword().equals(oldPassWord)) {
            return Result.error("原密码填写不正确");
        }
        // 比较两次密码是否一致
        if(!newPassWord.equals(rePassWord)){
            return Result.error("两次输入密码不一致");
        }
        updatePwd(newPassWord);
        return Result.success("修改密码成功");

    }
    @Override
    public Result<String> login(String userName, String userPwd){
        User loginUser = findUserByUserName(userName);
        if(loginUser == null){
            return Result.error("用户名不存在");
        }
        if(!userPwd.equals(loginUser.getPassword())){
            return Result.error("密码不正确");
        } else {
            //登录成功，生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            claims.put("role", loginUser.getRole());
            String token = JWTUtil.genToken(claims);
            return Result.success(token);
        }
    }

    /**
     * 更新用户个人信息
     * @param user
     * @return
     */
    @Override
    public Result updateDetail(User user) {
        user.setId(getUserIdFromToken());
        user.setUpdatedAt(LocalDateTime.now());
        if (user.getName().length() >= 15) {
            return  Result.error("用户名不能超过15个字");
        }
        return Result.success(userMapper.updateDetail(user));
    }

    @Override
    public Result getUserDetail() {
        // 获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println("map" + map);
        Integer id = (Integer) map.get("id");
        User user = userMapper.getUserDetail(id);
        return Result.success(user);
    }

    // 获取用户权限信息
    @Override
    public Result getUserInfo(){
        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user =  userMapper.getUserInfo(id);
        return Result.success(user);

    }

//    更新用户密码
    @Override
     public void updatePwd(String newPassWord){
//        获取用户的id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePassWord(newPassWord, id);
     }

//    更新用户头像
    @Override
    public void updateAvatar(String avatarUrl) {
//        获取用户的id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

//    更新用户信息
    @Override
    public void update(User user) {
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.update(user);
    }

    //    寻找用户根据用户名
    @Override
    public User findUserByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }
//     注册
    @Override
    public void register(String username, String password, String name, String email, String userAvatar) {
//     密码加密
//      添加到数据库
        userMapper.add(username,password,name,email,userAvatar);
    }

    public Result qiYeZhuCe(QiYeYongHu yongHu) {
        if(!yongHu.getPassword().equals(yongHu.getRePassword())) {
            return Result.error("两次输入的密码不一致");
        }
        // 密码长度不少于6位数
        if(yongHu.getPassword().length() < 6) {
            return Result.error("密码长度不少于6位数");
        }
        // 用户名不少于6位数
        if(yongHu.getPhone().length() < 6) {
            return Result.error("用户名长度不少于6位数");
        }
        User findUser = userMapper.findByUserName(yongHu.getPhone());
        if(findUser!= null) {
            return Result.error("该用户名已存在");
        }
        yongHu.setRole("customer");
        yongHu.setUsername(yongHu.getPhone());
        userMapper.addQiyeYongHu(yongHu);
        return Result.success("注册成功");
    }

    public Result qiYeYongHuGetUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User yongHu = userMapper.getUserById(id);
        return Result.success(yongHu);
    }

}
